package com.ikkong.platform.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.ikkong.common.vo.User;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.jfinal.ext.shiro.ClearShiro;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.toolbox.Record;
import com.ikkong.platform.meta.intercept.BlogIntercept;
import com.ikkong.platform.model.Blog;
import com.ikkong.platform.service.BlogService;
import com.ikkong.platform.service.impl.BlogServiceImpl;
import com.ikkong.school.model.Buy;
import com.ikkong.school.model.Suppliers;
import com.ikkong.system.controller.base.UrlPermissController;
import com.ikkong.system.model.Dept;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.PathKit;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.beetl.sql.core.kit.StringKit;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * Generated by Blade.
 * 2016-10-08 15:59:45
 */
public class BlogController extends UrlPermissController {
	private static String CODE = "blog";
	private static String PERFIX = "tb_tfw_blog";
	private static String LIST_SOURCE = "Blog.list";
	private static String BASE_PATH = "/platform/blog/";
	
	BlogService service = new BlogServiceImpl();
	
	public void index() {
		setAttr("code", CODE);
		render(BASE_PATH + "blog.html");
	}

    @ClearShiro
    public void paycompent() {
        Blog blog = new Blog();
        blog.setF_it_title("收款成功");
        blog.setF_it_createtime(new Date());
        boolean save = service.save(blog);
        if (save) {
            renderJson(success(UPDATE_SUCCESS_MSG));
        } else {
            renderJson(error(UPDATE_FAIL_MSG));
        }
    }

	public void add() {
//		setAttr("code", CODE);
//		render(BASE_PATH + "blog_add.html");
		String str  ="aa,aab,aac,aaa,aaaaa,ade";
		renderJson(Arrays.asList(str.split(",")));
	}

    @ClearShiro
	public void getAdminRegion() {
        String para = getPara(0, "0");
        List<Map> res = Blade.dao().select("Blog.address", Map.class, Record.create().set("parentno", para));
        renderJson(res);
	}
    @ClearShiro
    public void checkCompanyExists() {
        String para = getPara("companyName", "BBBBBBB");
        Integer res = Blade.dao().selectSingle("Blog.companyName", Record.create().set("name", para), Integer.class);
        boolean b = res>0?true:false;
        Map m = new HashMap();
        m.put("body",b);
        renderJson(m);
    }
    @ClearShiro
    public void checkUserExists() {
        String para = getPara("userName", "");
        Integer res = Blade.dao().selectSingle("Blog.checkUserExists", Record.create().set("username", para), Integer.class);
        boolean b = res>0?true:false;
        Map m = new HashMap();
        m.put("body",b);
        renderJson(m);
    }


    @ClearShiro
    @RequiresUser
    public  void downexcel(){
        String webRootPath = PathKit.getWebRootPath();
//        String list = getPara("ids");
//        List<String> strings = Arrays.asList(list.split(","));
        String uuid = UUID.randomUUID().toString();

        Buy b = new Buy();
        TemplateExportParams params = new TemplateExportParams(webRootPath+"/download/book.xlsx");

        Map<String, Object> map = new HashMap<String, Object>();
        String now = com.ikkong.system.util.DateUtil.dateToString(new Date(), "yyyy-MM-dd");
        map.put("dept", ShiroKit.getUser().getDeptName());
        map.put("now",now);
//        List<Buy> listMap = new ArrayList<Buy>();
//        int id=0;
//        for (int i=0;i< strings.size();i++){
//            if(StringKit.isBlank(strings.get(i))){
//                continue;
//            }
//            id = Integer.parseInt(strings.get(i));
//            Buy buy = Blade.create(Buy.class).findById(id);
//            buy.setId(i);
//            String time = "";
//            listMap.add(buy);
//        }


        List<Map> listMap = Blade.dao().select("Buy.list",Map.class,null);
        map.put("maplist", listMap);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        File savefile = new File(webRootPath+"/upload/");
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        try {
            FileOutputStream fos = new FileOutputStream(savefile+uuid+".xlsx");
            workbook.write(fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        renderFile(uuid+".xlsx","供应商对帐表.xlsx");
    }


    @ClearShiro
    @Before(POST.class)
    public void createCompanyWithLoginAdmin() {
        String companyName = getPara("companyName", "");//公司名
        String bizCertNum = getPara("certNo", "");
        String companyBizAddress = getPara("companyBizAddress", "");
        String companyNameAbbrev = getPara("companyNameAbbrev", "");
        String companyRegAddress = getPara("companyRegAddress", "");
        String loginUserMobile = getPara("loginUserMobile", "");
        String loginUserName = getPara("loginUserName", "");
        String loginUserPersonName = getPara("loginUserPersonName", "");
        String loginUserPsw = getPara("loginUserPsw", "");
        int regionCityId = getParaToInt("regionCityId", 1);
        int regionCountyId = getParaToInt("regionCountyId", 1);
        int regionStreetId = getParaToInt("regionStreetId", 1);
        String regionProvinceId = getPara("regionProvinceId", "");
        String webCompanyType = getPara("webCompanyType", "");
        Suppliers s = new Suppliers();
        User u = new User();
        Dept d = new Dept();
        d.setFullname(companyName);
        d.setVersion(0);
        d.setSimplename(companyName);
        d.setPid(7);
        d.setNum(0);
        int did = Blade.create(Dept.class).saveRtId(d);
        u.setAccount(loginUserName);
        String salt = ShiroKit.getRandomSalt(5);
        String pwdMd5 = ShiroKit.md5(loginUserPsw, salt);
        u.setPassword(pwdMd5);
        u.setSalt(salt);
        u.setName(companyName);
        u.setRoleid("8");
        u.setStatus(3);
        u.setDeptid(did);
        int uid = Blade.create(User.class).saveRtId(u);
        s.setU_id(uid);
        s.setD_id(did);
        s.setName(companyName);
        s.setProvince(regionCityId);
        s.setCity(regionCountyId);
        s.setCounty(regionStreetId);
        s.setAddress(companyRegAddress);
        s.setCode(bizCertNum);
        s.setConcat(loginUserPersonName);
        s.setTel(loginUserMobile);
        boolean save = Blade.create(Suppliers.class).save(s);
        if(save){
            renderJson(success("注册成功"));
        }else {
            renderJson(error("注册失败，请联系管理员"));
        }

    }

	public void edit() {
		String id = getPara(0);
		Blog blog = service.findById(id);
		setAttr("model", JsonKit.toJson(blog));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "blog_edit.html");
	}

	public void view() {
		String id = getPara(0);
		Blog blog = service.findById(id);
		setAttr("model", JsonKit.toJson(blog));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "blog_view.html");
	}

	public void list() {
		Object grid = paginate(LIST_SOURCE,new BlogIntercept());
		renderJson(grid);
	}

	public void save() {
		Blog blog = mapping(PERFIX, Blog.class);
		boolean temp = service.save(blog);
		if (temp) {
			renderJson(success(SAVE_SUCCESS_MSG));
		} else {
			renderJson(error(SAVE_FAIL_MSG));
		}
	}

	public void update() {
		Blog blog = mapping(PERFIX, Blog.class);
		boolean temp = service.update(blog);
		if (temp) {
			renderJson(success(UPDATE_SUCCESS_MSG));
		} else {
			renderJson(error(UPDATE_FAIL_MSG));
		}
	}

	public void remove() {
		String ids = getPara("ids");
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			renderJson(success(DEL_SUCCESS_MSG));
		} else {
			renderJson(error(DEL_FAIL_MSG));
		}
	}
}
